package com.mrcode.neptuneproject.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

/**
 * @Author YSH
 * @Date 2023/11/18 13:40
 * @Version 1.0
 */
@Slf4j
public class MyHttpUtils {

    /**
     * 发送Http Post请求
     *
     * @param requestUrl  url
     * @param requestBody body
     * @return result
     */
    public static String doPost(String requestUrl, String requestBody) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost req = new HttpPost(requestUrl);
        req.setConfig(RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000).build());
        req.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        req.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
        String responseBody = "";
        try {
            log.info("http post：request url is：" + requestUrl + "，body is：" + requestBody);
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(req);
            HttpEntity responseEntity = response.getEntity();
            responseBody = EntityUtils.toString(responseEntity);
            // 处理响应数据
            log.info("http post：request url is：" + requestUrl + "，response is:" + responseBody);
        } catch (Exception e) {
            throw new RuntimeException("http post error！ ERROR IS：" + e);
        }
        return responseBody;
    }
}
